package com.ljyhhh.SmartCity.base.database

import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import com.ljyhhh.SmartCity.base.user.User

object DBUtil {
    var dbHelper: DBHelper? = null
    var db:SQLiteDatabase? = null
    fun openDB(context: Context) {
        //获取SQLiteDatabase对象
        dbHelper = DBHelper(context)
        var db: SQLiteDatabase?
        try {
            db = dbHelper?.writableDatabase
        } catch (e: Exception) {
            db = dbHelper?.readableDatabase
        }
        this.db = db
    }

    fun closeDB(){
        //关闭输出输入
        if (db!!.isOpen){
            db?.close()
        }
    }

    fun qureyAll(context: Context) : MutableList<User>? {
        //更新全部数据
        openDB(context)
        var contactList: MutableList<User>? = mutableListOf()
        var cursor = db?.query("users",null,null,null,null,null,null)
        //cursor可以解释为指针,将指针移动到第一位，有就true，否则就false
        if(cursor!!.moveToFirst()){
            do{
                contactList?.add(User(username = cursor.getString(0), password = cursor.getString(1)))
                //将指针移动至下一条数据
            }while (cursor.moveToNext())
        }
        cursor.close()
        return contactList
    }
    fun qurey(context: Context,where:String): MutableList<User>? {
        openDB(context)
        val users: MutableList<User> = mutableListOf()
        val cursor=db?.rawQuery("select * from users where username like '$where%'",null)
        if(cursor!!.moveToFirst()){
            do{
                users?.add(User(username = cursor.getString(0), password = cursor.getString(1)))
                //将指针移动至下一条数据
            }while (cursor.moveToNext())
        }
        cursor.close()
        return users
    }

    fun remove(id: Int?,context: Context){
        openDB(context)

        db?.delete("users","username=?", listOf(id.toString()).toTypedArray())
    }

    fun updata(id:Int?,content:ContentValues,context: Context){
        //更新数据，ID查找更新
        openDB(context)
        db?.update("users",content,"username=?",listOf(id.toString()).toTypedArray())
    }

    fun add(content:ContentValues,context: Context){
        //增加一条数据
        openDB(context)

        db?.replace("users",null,content)
    }
}
